/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package nl.hanze.web.session;

import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import nl.hanze.web.banken.*;

/**
 *
 * @author Herman
 */
@Stateless
@TransactionManagement(TransactionManagementType.CONTAINER)
public class DistTransWebSB implements DistTransWebSBLocal {

    // Add business logic below. (Right-click in editor and choose
    // "Insert Code > Add Business Method")
    @PersistenceContext(unitName = "DerbyPU")
    private EntityManager DerbyEM;
    
    @PersistenceContext(unitName = "MyPU")
    private EntityManager MyEM;
    
    @Override
    public boolean transfer(int fromRekening, int toRekening, int amount) {
        // Eerst beide rekeningen zoeken
        Rekening from = findRekening(fromRekening);
        if (null == from)
            return false;
        Rekening to = findRekening(toRekening);
        if (null == to)
            return false;
        
        // Dan kijken of de verzender van geld genoeg saldo heeft
        if (from.getSaldo()-amount < -from.getLimiet())
            return false;
        
        // Dan de transactie uitvoerens
        from.addSaldo(-amount);
        to.addSaldo(amount);
        from.merge();
        to.merge();
        return true;
    }
    
    private Rekening findRekening(int rekNummer) {
        DerbyAccount da = DerbyEM.find(DerbyAccount.class, rekNummer);
        if (null != da) {
            da.setMerger(DerbyEM);
            return da;
        }
        MyAccount ma = MyEM.find(MyAccount.class, rekNummer);
        if (null != ma) {
            ma.setMerger(MyEM);
            return ma;
        }
        return null;
    }
}
